# coding: utf-8

from datetime import datetime

from flask import request, current_app
from flask_restful import Resource, abort

from app.api.views import SUCCESS
from app.constant import HttpCode
from app.token import AuthToken
from app.op.models import UserInfo
from common.constant import APP_USER_ID_KEY


class Response(object):
    """
    created by chenhj at 2017/8/11
    """
    def __new__(cls, code=SUCCESS, body=None):

        return dict(
            status=code.status,
            msg=code.msg,
            body=body
        )


class AppAuthResource(Resource):
    """
    create by ld_wu 2017-11-20
    App端需要认证的接口需要继承此类
    """

    def __init__(self, *args, **kwargs):
        self.user = None
        super(AppAuthResource, self).__init__(*args, **kwargs)

    @property
    def request_args(self):
        return request.args

    def dispatch_request(self, *args, **kwargs):
        token = request.headers.get('token')
        # 缺少token直接返回未认证
        if not token:
            abort(HttpCode.UNAUTHORIZED)
        user = AuthToken.verify_app_token(token)
        # token验证失败返回未认证
        if not user:
            abort(HttpCode.UNAUTHORIZED)
        self.user = user
        # 记录最后访问时间
        user_info = UserInfo.default_user_info(user.id)
        user_info.app_last_visit_time = datetime.now()
        current_app.redis.sadd(APP_USER_ID_KEY, user.id)
        return super(AppAuthResource, self).dispatch_request(*args, **kwargs)
